/**
 * mangodb 中间件
 */

//引入mongodb
import { ContextProp, DatabaseProps, ObjTypes } from "../appTypes";
import { client, config } from "../utils/mongoDb";


export const mongoDbMiddleware = async(ctx:ContextProp,next:any)=>{
  // 链接数据库
  await client.connect();
  const database: DatabaseProps = client.db(config.dataBase);
  async function getNextSequenceValue(sequenceName: string) {
    var sequenceDocument = await database.collection("counters").findOneAndUpdate({ _id: sequenceName }, { $inc: { sequence_value: 1 } });
    return sequenceDocument.value.sequence_value;
  }

  ctx.db = (collection_name: any) => {
    let mongidbObj = database.collection(collection_name);
    mongidbObj.insert = async (data: ObjTypes): Promise<any> => {
      var res = await database.collection("counters").find({ _id: `${collection_name}_id` }).toArray();
      if (res.length == 0) {
        // 不存在 ，新增改数据
        await database.collection("counters").insertOne({_id:`${collection_name}_id`,sequence_value:1});
      }
      let id = await getNextSequenceValue(`${collection_name}_id`);
      return await mongidbObj.insertOne({
        id:id,
        ...data
      });
    }
    return mongidbObj;
  };
  await next();
}